package org.jflame.captcha.creator;

import org.jflame.captcha.CaptchaUtils;
import org.jflame.commons.file.ImageHelper;
import org.jflame.commons.json.JsonHelper;

import java.awt.image.BufferedImage;
import java.beans.Transient;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

public class SimpleImage {

    private BufferedImage captchaImage;
    private transient String imageFormat;
    private transient boolean outJson = false;// 输出为json格式

    public SimpleImage(BufferedImage captchaImage) {
        this.captchaImage = captchaImage;
        imageFormat = CaptchaUtils.default_img_ext;
    }

    public SimpleImage(BufferedImage captchaImage, String imageFormat) {
        this.captchaImage = captchaImage;
        this.imageFormat = imageFormat;
    }

    public BufferedImage getCaptchaImage() {
        return captchaImage;
    }

    public void setCaptchaImage(BufferedImage captchaImage) {
        this.captchaImage = captchaImage;
    }

    @Transient
    public String getImageFormat() {
        return imageFormat;
    }

    public void setImageFormat(String imageFormat) {
        this.imageFormat = imageFormat;
    }

    @Transient
    public boolean isOutJson() {
        return outJson;
    }

    public void setOutJson(boolean outJson) {
        this.outJson = outJson;
    }

    public void write(OutputStream out) throws IOException {
        if (outJson) {
            JsonHelper.writeJSONString(out, ImageHelper.base64(captchaImage, imageFormat));
        } else {
            ImageIO.write(captchaImage, imageFormat, out);
        }
    }

}
